package com.yonyougov.devops.cruxcisupport.backupuser;

import com.yonyougov.devops.cruxcisupport.backupuser.dto.IssuedTestRequestDto;
import com.yonyougov.devops.cruxcisupport.backupuser.dto.ProcessPermissionsDto;
import com.yonyougov.devops.cruxcisupport.backupuser.dto.ProcessPermissionsRequestDto;
import com.yonyougov.devops.cruxcisupport.backupuser.dto.TestUserRequestDto;
import com.yonyougov.devops.cruxcisupport.constvar.DevOpsErrorCode;
import com.yonyougov.devops.fwc.api.dto.BaseResponseDto;
import com.yonyougov.devops.fwc.core.controller.CrudController;
import com.yonyougov.devops.fwc.core.service.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigInteger;

/**
 * Created by ligson on 2017/8/11.
 */
@Api(tags = "转测人模块")
@RestController
@RequestMapping("/api/v2/backupTestUser")
public class BackupTestUserController extends CrudController<BackupTestUserEntity, BigInteger> {

    private final BackupTestUserService backupTestUserService;

    public BackupTestUserController(BackupTestUserService backupTestUserService) {
        this.backupTestUserService = backupTestUserService;
    }

    @Override
    public BaseService<BackupTestUserEntity, BigInteger> getService() {
        return backupTestUserService;
    }

    //<!--用户自定义代码开始-->
    @ApiOperation(value = "转测按钮", notes = "转测")
    @PostMapping(value = "/issued")
    public BaseResponseDto issuedTest(@RequestBody @Valid IssuedTestRequestDto request) {
        backupTestUserService.issuedTestUsers(request);

        return BaseResponseDto.getSuccessInstance();
    }

    @ApiOperation(value = "根据提测Id获取测试人员", notes = "获取测试人员")
    @PostMapping(value = "/btu/names")
    public String getBackUserByCommitTestId(@RequestBody @Valid TestUserRequestDto request) {
        BigInteger commitTestId = request.getCommitTestId();

        return backupTestUserService.findTestUserByCommitTestId(commitTestId);
    }

    @ApiOperation(value = "检查身份为测试的用户是否具有操作提测单的权限", notes = "前端判断当前用户,仅仅当用户身份是测试的时候,此接口才允许调用")
    @PostMapping(value = "/btu/permissions")
    public BaseResponseDto processPermissions(@RequestBody @Valid ProcessPermissionsRequestDto request) {
        ProcessPermissionsDto processPermissionsDto = new ProcessPermissionsDto();
        BeanUtils.copyProperties(request, processPermissionsDto);

        boolean result = backupTestUserService.processPermissions(processPermissionsDto);

        if (result) {
            return BaseResponseDto.getSuccessInstance();
        } else {
            return BaseResponseDto.getFailInstance(DevOpsErrorCode.INSUFFICIENT_PERMISSION);
        }
    }
    //<!--用户自定义代码结束-->
}
